home *** CD-ROM | disk | FTP | other *** search
/ Magnum One / Magnum One (Mid-American Digital) (Disc Manufacturing).iso / d12 / snip9_91.arc / ALLOCA.C < prev    next >
C/C++ Source or Header  |  1991-09-17  |  1KB  |  46 lines

  1. /*
  2. ** By: John Navas 
  3. ** 
  4. ** Microsoft C v5.0 and QuickC include an alloca() library function,
  5. ** which allocates temporary storage from the stack.
  6. ** 
  7. ** The following function does the same job in Turbo C (tested in
  8. ** Version 1.5):
  9. */
  10.  
  11. #include <stdio.h>
  12.  
  13. typedef unsigned WORD;
  14.  
  15. char *alloca(WORD siz)          /* LOCAL STACK ALLOCATION IN TURBO C */
  16. {
  17. #if defined(__TINY__) || defined(__SMALL__) || defined(__COMPACT__)
  18.     extern WORD __brklvl;           /* stack check */
  19. #endif
  20.     static WORD len;                /* length rounded to words */
  21.     static int(*volatile rtn)();    /* return address */
  22.     static WORD volatile bp;        /* saved value of bp */
  23.  
  24.     if (_SP > (len = siz+1&~1)  /* stack check in words */
  25. #if defined(__TINY__) || defined(__SMALL__) || defined(__COMPACT__)
  26.     && __brklvl < _SP-len
  27. #endif
  28.     ) {
  29.         rtn = *(int(**)())((char*)&siz-sizeof(int(*)()));
  30.         bp = *(WORD*)((char*)&siz-sizeof(int(*)())-sizeof(WORD));
  31.         _SP -= len;
  32.         _BP -= len;
  33.         *(int(**)())((char*)&siz-sizeof(int(*)())) = rtn;
  34.         *(WORD*)((char*)&siz-sizeof(int(*)())-sizeof(WORD)) = bp;
  35.         return (char*)(&siz+1);
  36.     }
  37.     return 0;
  38. }
  39.  
  40. void main()
  41. {
  42.     char *p = alloca(80);
  43.  
  44.     printf("sp = %u\np  = %p\n", _SP, p);
  45. }
  46.